﻿using System;
using System.Security.Cryptography;
using System.Text;

namespace Smart.Business.Utils
{
    /// <summary>
    /// Use for MD5 password encryption
    /// </summary>
    public class EncryptionUtils
    {
        /// <summary>
        /// Method to encrypt string to MD5 hash code
        /// </summary>
        public static string Encrypt(string value)
        {
            return BaseEncryption(value);
        }

        /// <summary>
        /// Method to compare passwords
        /// </summary>
        public static bool Compare(string value, string encrypted)
        {
            return BaseEncryption(value).ToLower() == encrypted.ToLower();
        }

        private static string BaseEncryption(string value)
        {
            using (MD5 md5Hash = MD5.Create())
            {
                // Convert the input string to a byte array and compute the hash.
                byte[] data = md5Hash.ComputeHash(Encoding.UTF8.GetBytes(value));

                // Create a new Stringbuilder to collect the bytes
                // and create a string.
                StringBuilder sBuilder = new StringBuilder();

                // Loop through each byte of the hashed data 
                // and format each one as a hexadecimal string.
                for (int i = 0; i < data.Length; i++)
                {
                    sBuilder.Append(data[i].ToString("x2"));
                }

                // Return the hexadecimal string.
                return sBuilder.ToString();
            }
        }
    }
}
